<?php

namespace app\admin\controller;

/**
 * @title 订单相关
 */
class Order extends Common
{
    /**
     * @title 获取订单列表
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/order/query","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     * @param {"name":"uid","type":"int","required":true,"default":"","desc":"用户ID"}
     * @param {"name":"time","type":"int","required":true,"default":"","desc":"当前时间"}
     * @param {"name":"token","type":"int","required":true,"default":"","desc":"用户操作token"}
     * @param {"name":"page","type":"int","required":false,"default":"1","desc":"当前页数"}
     * @param {"name":"listRows","type":"int","required":false,"default":"10","desc":"获取条目数"}
     * @param {"name":"key","type":"int","required":false,"default":"","desc":"关键字"}
     * @param {"name":"goods_sn","type":"int","required":false,"default":"","desc":"商品编号完全匹配(通过商品编号其他参数将不生效)"}
     * @param {"name":"status","type":"int","required":false,"default":"","desc":"上线状态"}
     * @return {"name":"id","type":"int","required":true,"desc":"商品ID","level":1}
     * @return {"name":"title","type":"string","required":true,"desc":"商品名称","level":1}
     * @return {"name":"img","type":"string","required":true,"desc":"商品图片","level":1}
     * @return {"name":"price","type":"float","required":true,"desc":"商品价格","level":1}
     * @return {"name":"category_id","type":"int","required":true,"desc":"分类ID","level":1}
     * @return {"name":"content","type":"string","required":true,"desc":"商品介绍","level":1}
     * @return {"name":"add_time","type":"int","required":true,"desc":"添加时间","level":1}
     * @return {"name":"status","type":"int","required":true,"desc":"商品状态","level":1}
     * @return {"name":"sales","type":"int","required":true,"desc":"商品销量","level":1}
     * @return {"name":"business_id","type":"int","required":true,"desc":"所属商家","level":1}
     */
    public function query()
    {
        // order_id, order_sn, user_id, order_status, shipping_status, pay_status,
        // consignee, province, city, district, address, zipcode, mobile, order_amount,
        // total_amount, add_time, shipping_time, confirm_time, pay_time, transaction_id,
        // location, text, is_group
        $uid = $this->isCheckAuth();
        $goods = input("goods");
        $db = model("order");
        $field = "o.order_id as orderId,consignee,province,city,district,address,
        zipcode,mobile,total_amount as totalAmount,add_time as addTime,order_sn as orderSn,
        order_status as orderStatus,shipping_status as shippingStatus,pay_status as payStatus,
        shipping_time as shippingTime,pay_time as payTime,confirm_time as confirmTime,o.order_id as totalNum,o.order_id as totalPrice";
        $input = input("type");
        if ($input >= 0) {
            $db->where("o.order_status", $input);
        }
        if ($goods) {
            $field .= ",o.order_id as goodsList";
            $data = $db->alias("o")->field($field)->where("user_id", $uid)->select();
        } else {
            $data = $db->alias("o")->field($field)->where("user_id", $uid)->select();
        }
        $this->rest($data);

    }

    /**
     * @title 获取订单详情
     * @desc  {"0":"接口地址：http://api.huaxiaoujia.com/index/goods/detailed","1":"请求方式：GET","2":"接口备注：必传参数用于加密验证"}
     * @param {"name":"uid","type":"int","required":true,"default":"","desc":"用户ID"}
     * @param {"name":"time","type":"int","required":true,"default":"","desc":"当前时间"}
     * @param {"name":"token","type":"int","required":true,"default":"","desc":"用户操作token"}
     * @param {"name":"goods_id","type":"int","required":true,"default":"","desc":"商品ID"}
     * @return {"name":"id","type":"int","required":true,"desc":"商品ID","level":1}
     * @return {"name":"title","type":"string","required":true,"desc":"商品名称","level":1}
     * @return {"name":"img","type":"string","required":true,"desc":"商品图片","level":1}
     * @return {"name":"price","type":"float","required":true,"desc":"商品价格","level":1}
     * @return {"name":"category_id","type":"int","required":true,"desc":"分类ID","level":1}
     * @return {"name":"content","type":"string","required":true,"desc":"商品介绍","level":1}
     * @return {"name":"add_time","type":"int","required":true,"desc":"添加时间","level":1}
     * @return {"name":"status","type":"int","required":true,"desc":"商品状态","level":1}
     * @return {"name":"sales","type":"int","required":true,"desc":"商品销量","level":1}
     * @return {"name":"business_id","type":"int","required":true,"desc":"所属商家","level":1}
     */

    public function detailed()
    {
        $this->isCheckAuth();
        $uid = $this->isCheckAuth();
        $field = "o.order_id as orderId,consignee,province,city,district,address,
        zipcode,mobile,total_amount as totalAmount,add_time as addTime,order_sn as orderSn,
        order_status as orderStatus,shipping_status as shippingStatus,pay_status as payStatus,
        shipping_time as shippingTime,pay_time as payTime,confirm_time as confirmTime,o.order_id as goodsList";
        $orderId = input("order_id");
        if ($orderId) {
            $db = model("Order")->alias("o");
            $db->field($field)->join("k_order_goods g", "o.order_id = g.order_id");
            $data = $db->where(["user_id" => $uid, "o.order_id" => input("order_id")])->select();
            if ($data) {
                $this->rest($data);
            } else {
                $this->rest("没有找到相关订单", "s004");
            }
        } else {
            $this->rest("参数错误", "s004");
        }

    }

    /**
     * 修改订单状态
     */
    public function setOrderStatus()
    {
        $uid = $this->isCheckAuth();
        $order_id = input('post.order_id');
        $order_status = input('post.order_status');
        $where = array(
            'order_id' => $order_id,
            'user_id' => $uid
        );
        $res = db('order')->where($where)->update(['order_status' => $order_status]);
        if ($res === false) {
            $this->rest("修改失败");
        } else {
            $this->rest("修改成功");
        }

    }

    /**
     * 创建订单
     */
    public function insertOrder()
    {
        $uid = $this->isCheckAuth();
        //通过用户ID查询结算的商品
        $field = "id,c.goods_id as goodsId,c.goods_name as goodsName,g.original_img as originalImg,c.goods_price as goodsPrice,goods_num as goodsNum,spec_id as specId";
        $cartData = model('Cart')->alias("c")->field($field)->join("k_goods g", "c.goods_id=g.goods_id")->where(['user_id' => $uid, "selected" => 1])->select();
        $cartTotalPrice = db("cart")->where(['user_id' => $uid, "selected" => 1])->sum('goods_price * goods_num');
        if (!$cartData) {
            $this->rest("选择没有商品", "s004");
        }
        //查询收货地址
        $addressId = input("address_id");
        $address = db("user_address")->where(["user_id" => $uid, "address_id" => $addressId])->find();
        if (!$address) {
            $this->rest("请填写收货地址", "s004");
        }
        $order = $this->addOrder($uid, $address, $cartTotalPrice);
        if ($order) {
            $this->moveCartToOrder($order["orderId"], $cartData);
            $this->rest($order);
        } else {
            $this->rest("创建订单失败", "s004");
        }
    }

    /**
     * 添加订单
     * @param $uid
     * @param $address
     * @param $cartTotalPrice
     * @return $orderId;
     */
    private function addOrder($uid, $address, $cartTotalPrice)
    {
        $orderData = array(
            'order_sn' => date('YmdHis') . rand(1000, 9999), // 订单编号
            'user_id' => $uid, // 用户id
            'consignee' => $address['consignee'], // 收货人
            'province' => $address['province'], //省
            'city' => $address['city'], //市
            'district' => $address['district'], //县
            'address' => $address['address'], //'详细地址',
            'mobile' => $address['mobile'], //'手机',
            'zipcode' => $address['zipcode'], //'邮编',
            'total_amount' => $cartTotalPrice, // 订单总额
            'order_amount' => $cartTotalPrice, //'应付款金额',
            'add_time' => time(), // 下单时间
            'location' => $address['zipcode'], //下单区域
            'is_group' => 0,
        );
        $orderId = db("order")->insertGetId($orderData);
        return array("orderId" => $orderId, "orderSn" => $orderData["order_sn"], "price" => $cartTotalPrice);
    }

    /**
     * 移动购物车商品到订单商品
     */
    private function moveCartToOrder($orderId, $cartData)
    {
        //rec_id, order_id, goods_id, goods_name, goods_sn, goods_num, market_price, goods_price, cost_price,
        //member_goods_price, give_integral, spec_id, bar_code, is_comment, prom_type, prom_id, is_send, delivery_id, sku
        foreach ($cartData as $k => $v) {
            $orderGoods = array(
                "order_id" => $orderId,
                "goods_id" => $v["goodsId"],
                "goods_name" => $v["goodsName"],
                "goods_num" => $v["goodsNum"],
                "goods_price" => $v["goodsPrice"],
                "spec_id" => $v["specId"],
            );
            db("order_goods")->insert($orderGoods);
            db("cart")->delete($v["id"]);
        }
    }
}
